﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using ZXing;

public class WebCameraPanel : MonoBehaviour
{
    WebCamTexture camTexture;
    RawImage rawImage;
    public Action SuccessRead;

    void Start()
    {
        mReader = new BarcodeReader();
        camTexture = new WebCamTexture();
        rawImage = GetComponent<RawImage>();
        WebCamDevice[] devices = WebCamTexture.devices;
        if (devices.Length>0)
        {
            if (devices.Length>1)
            {
                foreach (var item in devices)
                {
                    if (!item.isFrontFacing)
                    {
                        CreateWebcamTex(item.name);
                        break;
                    }
                }
            }
            else
            {
                CreateWebcamTex(devices[0].name);
            }
        }
    }

    public void StartReadQrCode(Action <string>action)
    {
        StartCoroutine(IEUpdate(action));
    }

    private BarcodeReader mReader;
    public string Decode(Color32[] colors, int width, int height)
    {
        var result = mReader.Decode(colors, width, height);
        if (result != null)
        {
            return result.Text;
        }
        return null;
    }

    private void CreateWebcamTex(string deviceName)
    {
        camTexture = new WebCamTexture(deviceName, 1280, 720);
        rawImage.texture = camTexture;
        camTexture.Play();
        Debug.Log("开启成功！！！");
    }

    IEnumerator IEUpdate(Action <string>Success)
    {
        while (true)
        {
            yield return new WaitForSeconds(0.2F);
            if (camTexture != null && camTexture.width > 100)
            {
                string result = Decode(camTexture.GetPixels32(), camTexture.width, camTexture.height);
                if (!string.IsNullOrEmpty(result))
                {
                    camTexture.Stop();
                    StopAllCoroutines();
                    //识别成功后做相应操作
                    Success(result);
                }
            }
        }
    }
}
